package manage.handler;

import manage.entity.AdminDo;
import manage.service.AdminService;
import manage.service.impl.AdminServiceImpl;
import manage.student.LoginView;
import manage.student.MainView;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class LoginHandler extends KeyAdapter implements ActionListener {
    private LoginView loginView;
    public LoginHandler(LoginView loginview){
        this.loginView=loginview;
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        JButton jButton=(JButton) e.getSource();
        String Text=jButton.getText();
        if(Text.equals("登录")){
            login();
        } else if (Text.equals("重置")) {
          loginView.getUserText().setText("");
          loginView.getPwdText().setText("");
        }
    }

    private void login() {
        //System.out.println("登录");
        String user=loginView.getUserText().getText();
        String pwd=loginView.getPwdText().getText();
        //检验
        if(user==null||"".equals(user.trim())||pwd==null){
            JOptionPane.showMessageDialog(loginView,"用户名密码错误");
            return;
        }
        System.out.println(user+"\n"+pwd);
        //数据库检验链接
        AdminService adminService=new AdminServiceImpl();
        AdminDo adminDo=new AdminDo();
        adminDo.setUserName(user);
        adminDo.setPwd(pwd);
        boolean flag=adminService.validateAdmin(adminDo);

        if(flag){//登陆成功
            //跳转到主界面并关闭登录界面
            new MainView();
            loginView.dispose();
        }else{
            JOptionPane.showMessageDialog(loginView,"登录失败");
        }
    }

    @Override
    public void keyPressed(KeyEvent e) {
        if(e.getKeyCode()==KeyEvent.VK_ENTER){
            login();
        }
    }
}
